﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using Vita.Entities;
using Vita.Entities.Services;

namespace Vita.Modules.BackgroundTasks {

  public class BackgroundTaskRunner {
    string _instanceId; 
    ITimerService _timerService; 

    public BackgroundTaskRunner(EntityApp app) {
      _instanceId = app.AppName + ":BackgroundTaskRunner";
      _timerService = app.GetService<ITimerService>();
      if (!TryActivate()) { //wait in timer for activation
        _timerService.Elapsed1Second += TimerService_Elapsed1Second;
      }
    }
    public bool IsActive {
      get { return _isActive; }
    } bool _isActive; 

    void TimerService_Elapsed1Second(object sender, EventArgs e) {
      if (TryActivate())
        _timerService.Elapsed1Second -= TimerService_Elapsed1Second;
    }

    Semaphore _semaphore;
    bool TryActivate() {
      if (IsActive)
        return true; 
      _semaphore = new Semaphore(0, 1, _instanceId, out _isActive);
      if (!_isActive) {
        _semaphore.Dispose();
        _semaphore = null;
      }
      return IsActive;
    }

    


  }
}
